package handler;

import entity.AdminDO;
import service.StudentService;
import service.impl.AdminServiceImpI;
import service.impl.StudentServiceImpI;
import view.AddStudentView;
import view.LoginView;
import view.MainView;
import view.UpdateStudentView;

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;

public class MainViewHandler implements ActionListener {
    private MainView mainView;

    public MainViewHandler(MainView mainView) {
        this.mainView = mainView;
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        JButton jButton = (JButton) e.getSource();
        String text = jButton.getText();
        if ("增加".equals(text)) {
            new AddStudentView(mainView);

        } else if ("修改".equals(text)) {
            int[] selectStudentIds = mainView.getSelectStudentIds();
            if (selectStudentIds.length != 1) {
                JOptionPane.showMessageDialog(mainView, "一次只能修改一个");
                return;
            }
            new UpdateStudentView(mainView, selectStudentIds[0]);
        } else if ("删除".equals(text)) {
            int[] selectStudentIds = mainView.getSelectStudentIds();
            if (selectStudentIds.length == 0) {
                JOptionPane.showMessageDialog(mainView, "请选择要删除的行");
                return;
            }
            int option = JOptionPane.showConfirmDialog(mainView, "确认删除所选择的" + selectStudentIds.length + "行吗？", "确认删除", JOptionPane.YES_NO_OPTION);
            if (option == JOptionPane.YES_OPTION) {//确认
                //执行删除
                StudentService studentService = new StudentServiceImpI();
                boolean deleteResult = studentService.delete(selectStudentIds);
                if (deleteResult) {
                    //重新加载表格
                    mainView.reloadTable();
                    //updateStudentView.dispose();
                } else {
                    JOptionPane.showMessageDialog(mainView, "删除失败");
                }
            }
        } else if ("查询".equals(text)) {
            mainView.setPageNow(1);
            mainView.reloadTable();
        } else if ("上一页".equals(text)) {
            mainView.setPageNow(mainView.getPageNow() - 1);
            mainView.reloadTable();
        } else if ("下一页".equals(text)) {
            mainView.setPageNow(mainView.getPageNow() + 1);
            mainView.reloadTable();
        }
    }
}
